# -*- coding: utf-8 -*-
import datetime
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.cache import redis_cache
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError
from common.utils.tz import utc_to_local_str1

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'https://gateway.aiispay.com/recharge/pay'
_QUERY_GATEWAY = 'https://gateway.aiispay.com/recharge/query'

# MCH_NO=100001
# APP_ID=WEBeac34a76d9daaed375ded7a61c967
# KEY=$2y$10$W/VqJWk5GOK1Q61W4p/6D.g5a8FZvwd0v9sYn1Jn7d923okuViEWe
APP_CONF = {
    '100006': {
        'API_ID': 'WEBc6758900480be6d96c8013c44e25c',
        'API_KEY': '$2y$10$rkZRcigHTIsbNoEhqyDZy.JZWxWZZH6.Tsp68q/X34zz/gqVFcDxy',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_api_id(mch_id):
    return APP_CONF[mch_id]['API_ID']


def generate_sign(parameter, key):
    s = ''
    for k in sorted(parameter.keys()):
        s += '%s=%s&' % (k, parameter[k])
    s += key
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().lower()
    return sign


def verify_notify_sign(params, key):
    sign = params.pop('sign')
    calculated_sign = generate_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("aishangpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


def _build_form(params):
    html = u"<head><title>loading...</title></head><form id='submit' name='submit' action='" + _GATEWAY + "' method='post'>"
    for k, v in params.items():
        html += "<input type='hidden' name='%s' value='%s'/>" % (k, v)
    html += "</form>"
    html += "<script>doc" \
            "ument.forms['submit'].submit();</script>"
    return html


# 微信 WAP	weixin_wap
# 支付宝 WAP	alipay_wap
# QQWAP	qq_wap
def _get_pay_type(service):
    if service == 'wxpay':
        payType = 'weixin_wap'
    elif service == 'alipay':
        payType = 'alipay_wap'
    elif service == 'qq':
        payType = 'qq_wap'
    else:
        payType = 'alipay_wap'
    return payType


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    appid = _get_api_id(mch_id)
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('version', '1.0'),
        ('mch_code', mch_id),
        ('mch_no', str(pay.id)),
        ('order_amt', str(pay_amount)),
        ('app_id', appid),
        ('callback_url', '{}/pay/api/{}/aishangpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('return_url', '{}/pay/api/{}/aishangpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, mch_id)),
        ('recharge_type', _get_pay_type(service)),
        ('order_time', utc_to_local_str1(datetime.datetime.now())),
        ('sign_type', 'md5'),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, key)
    _LOGGER.info("aishangpay create date: %s", parameter_dict)
    html_text = _build_form(parameter_dict)
    _LOGGER.info("aishangpay create html: %s", html_text)
    cache_id = redis_cache.save_html(pay.id, html_text)
    charge_resp = {
        'charge_info': settings.PAY_CACHE_URL + cache_id,
    }
    return charge_resp


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.POST.iteritems())
    _LOGGER.info("aishangpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['mch_no']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('aishangpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['err_code'])
    trade_no = data['plat_no']
    total_fee = float(data['order_amt'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 0为成功 其余为失败
    if trade_status == 0:
        _LOGGER.info('aishangpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pay_id = pay_order.id
    key = _get_api_key(app_id)
    p_dict = {
        'version': '1.0',
        'mch_code': app_id,
        'mch_no': str(pay_id),
        'sign_type': 'md5',
    }
    p_dict['sign'] = generate_sign(p_dict, key)
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    _LOGGER.info(u'aishangpay query: %s', response.text)
    data = json.loads(response.text)
    if response.status_code == 200:
        trade_status = int(data['state'])  # 0 订单未成功 1订单成功
        total_fee = float(data['order_amt'])
        trade_no = data['system_no']
        extend = {
            'trade_status': trade_status,
            'trade_no': trade_no,
            'total_fee': total_fee
        }

        if trade_status == 1:
            _LOGGER.info('aishangpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
            res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
            if res:
                async_job.notify_mch(pay_order.id)
    else:
        _LOGGER.warn('aishangpay data error, status_code: %s', response.status_code)


if __name__ == '__main__':
    p_dict = {
        'version': '1.0',
        'mch_code': '100001',
        'mch_no': '1627329203596689408',
        'sign_type': 'md5',
    }
    p_dict['sign'] = generate_sign(p_dict, '$2y$10$W/VqJWk5GOK1Q61W4p/6D.g5a8FZvwd0v9sYn1Jn7d923okuViEWe')
    headers = {'Content-Type': 'application/json;charset=utf-8'}
    response = requests.post(_QUERY_GATEWAY, data=json.dumps(p_dict), headers=headers, timeout=10)
    print response.text
